package org.arch_learn.netty_rpc.consumer.proxy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.arch_learn.netty_rpc.consumer.netty_client.NettyRpcClient;
import org.arch_learn.netty_rpc.netty_rpc_api.common.RpcRequest;
import org.arch_learn.netty_rpc.netty_rpc_api.common.RpcResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.Type;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 客户端代理类--创建代理对象
 * 1.封装request请求对象
 * 2.创建RpcClient对象
 * 3.发送消息
 * 4.返回结果
 */
@Component
public class NettyRpcClientProxy {
    @Autowired
    private List<NettyRpcClient> nettyRpcClients;

    private AtomicInteger requestCount = new AtomicInteger(0);

    public Object createProxy(Class serviceClass) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{serviceClass}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("==========执行NettyRpcClientProxy.invoke()方法，执行代理");
                        //1.
                        RpcRequest rpcRequest = new RpcRequest();
                        rpcRequest.setRequestId(UUID.randomUUID().toString());
                        rpcRequest.setClassName(method.getDeclaringClass().getName());
                        rpcRequest.setParameterTypes(method.getParameterTypes());
                        rpcRequest.setMethodName(method.getName());
                        rpcRequest.setParameters(args);
                        //2.
                        NettyRpcClient rpcClient = null;
                        try {
                            //3.
                            requestCount.incrementAndGet();
                            int i = requestCount.get() % (nettyRpcClients.size());
                            rpcClient = nettyRpcClients.get(i);
                            Object resultMessage = rpcClient.send(JSONObject.toJSONString(rpcRequest));
                            RpcResponse rpcResponse = JSONObject.parseObject(resultMessage.toString(), RpcResponse.class);
                            if (rpcResponse.getError() != null) {
                                throw new RuntimeException(rpcResponse.getError());
                            }
                            //4.
                            Object result = rpcResponse.getResult();
                            Type returnType = method.getReturnType();

                            return JSON.parseObject(result.toString(), returnType);
                        } catch (Exception e) {
                            throw e;
                        }
                        //这里不能close因为我这里是始终只有两个客户端实例
//                        finally {
//                            rpcClient.close();
//                        }
                    }
                }
        );
    }
}
